<template>
  <el-card class="form-container" shadow="never">
    <el-checkbox-group v-model="checkedWorkShops" ref="cg">
      <el-checkbox v-for="ws in workShops" :label="ws.id" :key="ws.id">{{ws.name}}</el-checkbox>
    </el-checkbox-group>
    <div style="margin-top: 20px" align="center">
      <el-button type="primary" @click="handleSave()">保存</el-button>
      <el-button @click="handleClear()">清空</el-button>
    </div>
  </el-card>
</template>

<script>
  import {workshops} from '@/api/workshop';
  import {allocRoleWorkshop, checkedWorkshops} from '@/api/role';

  export default {
    name: "allocWorkShop",
    data() {
      return {
        roleId:null,
        workShops: [],
        checkedWorkShops: []
      };
    },
    created() {
      this.roleId = this.$route.query.roleId;
      this.getWorkShops();
      this.getCheckedWorkShops(this.roleId);
    },
    methods: {
      getWorkShops(){
        workshops().then(response => {
          this.workShops = response.data;
        })
      },
      getCheckedWorkShops(roleId) {
        checkedWorkshops(roleId).then(response => {
          this.checkedWorkShops = response.data;
        })
      },
      handleSave() {
        this.$confirm('是否分配车间？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(()=>{
          let params = new URLSearchParams();
          params.append("roleId",this.roleId);
          params.append("workshopIds",Array.from(this.checkedWorkShops));
          allocRoleWorkshop(params).then(response => {
            this.$message({
              message: '分配成功',
              type: 'success',
              duration: 1000
            });
            this.$router.back();
          })
        })
      },
      handleClear() {
        this.checkedWorkShops = new Array();
      }
    }
  }
</script>
